<template>
    <div class="e-form">
        <div class="tabs" v-if="Object.keys(formData).length != 0">
             <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                 <!-- 基本信息 -->
                <el-tab-pane label="设备信息" name="equipInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="价格信息" name="basePrice" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="equipInfoCon">
                        <div class="tabs-title" id="equipInfo">设备信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.basicPrice" :rules="rules" label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="选择年月：" prop="billDate">
                                            <el-date-picker
                                                v-model="formData.basicPrice.billDate"
                                                type="month"
                                                value-format="yyyy-MM"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入日期：">
                                            <span>{{ formData.basicPrice.gmtCreate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ formData.basicPrice.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="basePriceCon">
                        <div class="tabs-title" id="basePrice">价格信息</div>
                        <div style="width: 100%" class="e-table">
                            <div class="top">
                                <div class="left">
                                    <el-button size="mini" class="btn-blue" @click="selectEquip">选择基础库设备</el-button>
                                    <el-button size="mini"  @click="deletePlanList">删除</el-button>
                                </div>
                            </div>
                            <el-table
                                ref="planTable"
                                :data="formData.basicPriceSettingList"
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :cell-class-name="cellClsNm"
                                @selection-change="planTableSelect"
                                class="table"
                                v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column prop="equipmentNo" label="设备编号" min-width="200" ></el-table-column>
                                <el-table-column prop="equipmentName" label="设备名称" width="200"></el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    width="120"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="120"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.unit ? unitMeasure.find(x=>x.value === row.unit).label : ''}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="计时单位"
                                    width="120"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.timeUnit ? timeUnitList.find(x=>x.value === row.timeUnit).label : ''}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="marketPrice"
                                    label="市场价格（元）"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model.number="row.marketPrice" clearable @change="row.changeType = 2"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="onlinePrice"
                                    label="网上价格（元）"
                                    width="180"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model.number="row.onlinePrice" clearable @change="row.changeType = 2"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
         <div class="buttons">
                <el-button
                    type="primary"
                    size="small"
                    class="btn-blue"
                    @click="preserve"
                    >保存</el-button
                >
                <el-button
                    type="primary"
                    size="small"
                    class="btn-red"
                    @click="onDel"
                >删除</el-button>
                <el-button size="small" @click="handleClose">取消</el-button>
            </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
import { formatDate } from '@/utils/common.js'
import { selectDataClient } from '@/utils/common'
export default {
    data () {
        return {
            // dialogVisible: false,
            // fullscreen: false,
            tabsName: 'equipInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
            },
            stateList: [
                {
                    label: '停用',
                    value: '1'
                },
                {
                    label: '启用',
                    value: '2'
                },
            ], //设备状态
            rules: {
                billDate: [
                    { required: true, message: '请选择年月', trigger: 'blur' },
                ],
            },
            tableData: [],
            planSelect: [],
            errorMsg: []
        }
    },
    props: {
        isEdit: {
            type: String,
            default: ''
        },
        equipData: {
            type: Object,
            default: ()=>{}
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            unitMeasure: state => state.equip.equipData.unitMeasure, //计量单位
            timeUnitList: state => state.equip.equipData.timeUnitList, //计量单位
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.userName = localStorage.getItem('userName')
        if(this.isEdit === 'add') {
            this.formData = {
                'basicPrice': {
                    'billDate': '',
                    'billId': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'orgId': '',
                    'orgName': '',
                    'recorderDate': ''
                },
                'basicPriceSettingList': []
            }
            let date  = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
            let date1  = formatDate(new Date(), 'yyyy-MM')
            this.formData.basicPrice.gmtCreate = date
            this.formData.basicPrice.billDate = date1
            this.formData.basicPrice.orgName = this.userInfo.orgInfo.orgName
            this.formData.basicPrice.orgId = this.userInfo.orgInfo.orgId
        }
        else if(this.isEdit === 'edit') {
            this.formData = this.equipData
        }
        this.getDicValue()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['equipInfo', 'basePrice']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setUnitMeasur')//更新计量单位
            this.$store.dispatch('equip/setTimeUnitList')//更新计时单位
        },
        //保存
        preserve () {
            this.$refs.form.validate(valid=>{
                if(valid) {
                    this.errorMsg = []
                    const isTwoDecimal = value => {
                        const age = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
                        return age.test(value)
                    }
                    this.formData.basicPriceSettingList.forEach((item, index)=>{
                        if(item.marketPrice === '' || item.marketPrice === null) {
                            let str = `请填写第 ${index} 行的 （ 市场价格 ），`
                            this.errorMsg.push(str)
                        }
                        else if(!isTwoDecimal(item.marketPrice)) {
                            let str = `第 ${index} 行的 （ 市场价格 ）需保留两位小数，`
                            this.errorMsg.push(str)
                        }
                        if( item.onlinePrice === '' || item.onlinePrice === null) {
                            let str = `请填写第 ${index} 行的 （ 网上价格 ），`
                            this.errorMsg.push(str)
                        }
                        else if(!isTwoDecimal(item.onlinePrice)) {
                            let str = `第 ${index} 行的 （ 网上价格 ）需保留两位小数，`
                            this.errorMsg.push(str)
                        }
                    })
                    if(this.errorMsg.length > 0) {
                        return
                    }else{
                        this.$emit('save', this.formData)
                    }
                }
            })
        },
        onDel () {
            this.$emit('del', this.formData.basicPrice)
        },
        //取消
        handleClose () {
            this.$emit('onCancel')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        selectEquip () {
            const that = this
            selectDataClient({
                SelectServiceToken: '/facilityplan/list/account/equipment', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '选择台账' // 标题
            }).then(val => {
                const obj = {
                    'accountId': '',
                    'billDate': '',
                    'changeType': 0,
                    'equipmentId': '',
                    'equipmentName': '',
                    'equipmentNo': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'marketPrice': 0,
                    'modifier': '',
                    'modifierId': '',
                    'onlinePrice': 0,
                    'orgId': '',
                    'orgName': '',
                    'priceSettingId': '',
                    'recorder': '',
                    'recorderId': '',
                    'specificationModel': '',
                    'standingBookType': 0,
                    'timeUnit': '',
                    'unit': '',
                    ...val[0]
                }
                that.formData.basicPriceSettingList = [obj]
                this.$refs.planTable.doLayout()
            }).catch(err=>{
                alert(err)
            })
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        //删除计划明细列表
        deletePlanList () {
            this.formData.basicPriceSettingList = []
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

</style>
